package basicelement;

import istar.IElement;
import istar.agent.IstarJadeAgent;
import istar.behaviour.AbstractIstarBehaviour;
import istar.impl.AbstractBasicTask;
import jade.core.behaviours.Behaviour;
import jade.lang.acl.ACLMessage;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;

import com.rapidminer.RapidMiner;
import com.rapidminer.example.Attribute;
import com.rapidminer.example.Example;
import com.rapidminer.example.ExampleSet;
import com.rapidminer.operator.IOContainer;
import com.rapidminer.operator.Operator;
import com.rapidminer.operator.io.ExampleSource;
import com.rapidminer.tools.OperatorService;

public class SeekNextStockOptionQuotation extends AbstractBasicTask{

	private boolean log = true;
	//private String pathToFile = "D:\\Documents and Settings\\csid\\Meus documentos\\rm_workspace\\VALE5\\VALE5-JAN15-TEST-MAX-MAI-JUN-2009.aml";
	//private String pathToFile = "D:\\Documents and Settings\\csid\\workspace\\Fanxaria\\file\\dataset\\VALE5-JAN15-TEST-MAX-MAI-JUN-2009.aml";
	private HashMap<String, String> quotations = null;
	private boolean done = false;
	
	public SeekNextStockOptionQuotation() {
		super("SeekNextStockOptionQuotation");
	}
	
	@Override
	public Behaviour getBehaviour() {
		return new myBehaviour(this);
	}
	
	private class myBehaviour extends AbstractIstarBehaviour{

		private int estimatedTime = 5000;
		boolean isFile = true;
		String stockOptionFile = "";
		
		
		public myBehaviour(AbstractBasicTask _task){
			super(_task);
			//task = _task;
			//this.setElement(_task);
			this.setBehaviourName("SeekNextStockOptionQuotation");

		}
		
		@Override
		public long getEstimatedWaitingTime() {
			return estimatedTime;
		}

		
		@Override
		public void myAction() throws Exception {
			
			BufferedReader in = new BufferedReader(new FileReader(((IstarJadeAgent)myAgent).configurationPath));
		    String str;
		    while ((str = in.readLine()) != null) {
		        if (str.startsWith("StockPricesFile=")){
		        	stockOptionFile = str.substring(16);
		        	break;
		        }
		    }
		    in.close();

			
            String simulationTime= "";
            // getting quotation parameter
            
            ACLMessage msg = ((IstarJadeAgent)myAgent).getWorkingMessages().get(getElement().getExecutionNumber());
			
            String msgContent = ((ArrayList<String>)msg.getContentObject()).get(0);
           
            /*
			if (msgContent.contains("simulation_time=")){
				int init = msgContent.indexOf("simulation_time=") + 16;
				while (msgContent.charAt(init)!='>'){
					simulationTime += msgContent.charAt(init);
					init++;
				}
			}
			*/

			if (msgContent.contains("SimulationTime=")){
				int i = msgContent.indexOf("SimulationTime=") + 15;
				simulationTime = msgContent.substring(i,i+16);
				System.out.println("SimulationTime="+simulationTime);
			}
			else 
				throw new Exception("Wrong parameter: " + msgContent);
            
			Example example = this.getNextStockOptionQuotationFromFile(simulationTime, stockOptionFile);

			ACLMessage reply = msg.createReply();
			msg.setPerformative(ACLMessage.INFORM);
            reply.setContentObject(example);

			myAgent.send(reply);
            done = true;
				
		}
		
		
		private Example getNextStockOptionQuotationFromFile(String _time, String pathToFile){
			Operator stockOptionPrices = null;
			try {
				stockOptionPrices = OperatorService.createOperator(ExampleSource.class);
			} catch (Exception e) { 
					// invoke init before using the OperatorService
					//RapidMiner.init(true, false, false, false);
					RapidMiner.init();
					System.out.println(this.getBehaviourName()+ " rodou RapidMiner.init()");
					try {
						stockOptionPrices = OperatorService.createOperator(ExampleSource.class);
					} catch (Exception e2) {
						e.printStackTrace();
					}
			}

				try {
					stockOptionPrices.setParameter("attributes", pathToFile);
					IOContainer stockOptionContainer = stockOptionPrices.apply(new IOContainer());
					ExampleSet resultSet = stockOptionContainer.get(ExampleSet.class);
					//Attribute quotationTime= resultSet.getAttributes().get("Date");
					Attribute timeAtt= resultSet.getAttributes().getId();
					int i=0;
					Example ex = resultSet.getExample(i);
					System.out.println(ex);
					String exTime =ex.getValueAsString(timeAtt); 
					
					while (!exTime.equals(_time) && i<resultSet.size()-1){
						i++;
						exTime = resultSet.getExample(i).getValueAsString(timeAtt);
					}
					ex = resultSet.getExample(i+1);
					System.out.println("StockOption quotation: " + ex.toString());
					return ex;
					
					// add operator to process
					//process.getRootOperator().addOperator(testSourceMax);
				} catch (Exception e) { 
					e.printStackTrace ();
					return null;
				}	
		}
		

		public int myOnEnd() {
			if (done){
				log("Agent name="+ myAgent.getName() +" ending behaviour:"+ this.getBehaviourName());
				return 1;
			}
			else
				return 0;
		}
		

		@Override
		public boolean done() {
			return true;
		}
		
	}
	

}
